import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import child_process from 'child_process'
import fs from 'fs';
import path from "path";

const server = new McpServer({
  name: "swagger2-doc-mcp",
  version: "1.0.0"
});

server.tool(
  "fetch",
	"get swagger doc to local file system",
  { url: z.string(), target: z.string() },
  async ({ url, target }) => {
    console.log(`swagger2-doc-parser fetch ${url} -d ${target}`)
    fs.writeFileSync(path.resolve(__dirname, "./fetch.json"), JSON.stringify({ url, target }), {
      encoding: "utf-8"
    })
    child_process.exec(`swagger2-doc-parser fetch ${url} -d ${target}`)
		return {
			content: [{
				type: "text",
				text: `got swagger doc ${url} to target file ${target}`
			}]
		};
  }
);

server.tool(
  "gen",
	"genarate code with swagger doc",
  { config: z.string(), source: z.string(), output: z.string() },
  async ({ config, output, source }) => {
    console.log(`swagger2-doc-parser gen -c ${config} -o ${output} -d ${source}`)
    child_process.exec(`swagger2-doc-parser gen -c ${config} -o ${output} -d ${source}`)
		return {
			content: [{
				type: "text",
				text: `genarated code with config ${config},parse swagger doc source file ${source} to ouput dir ${output}`
			}]
		};
  }
);


server.prompt(
  "fetch",
	{ url: z.string(), target: z.string() },
  ({ url, target }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `Please get swagger doc ${url} to target file ${target}`
      }
    }]
  })
);

server.prompt(
  "gen",
  { config: z.string(), source: z.string(), output: z.string() },
  ({ config, output, source }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `Please gen code with config ${config},parse swagger doc source file ${source} to ouput dir ${output}`
      }
    }]
  })
);


async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("Swagger2 Doc MCP Server running on stdio");
}

main().catch((error) => {
  console.error("Fatal error in main():", error);
  process.exit(1);
});